"""
服务特定数据库配置示例
====================

展示如何为不同的微服务定义独立的数据库配置
每个服务拥有自己的数据库Schema和连接配置
"""

from pydantic import Field
from typing import Dict, Any
from redfire_framework.core.config import (
    RedFireSettings, 
    SingleDatabaseServiceMixin, 
    MultiDatabaseServiceMixin
)


# ========================================
# 1. 用户服务 - 单数据库配置
# ========================================

class UserServiceSettings(RedFireSettings, SingleDatabaseServiceMixin):
    """
    用户服务配置
    
    用户服务只需要一个MySQL数据库来存储用户信息
    """
    
    # 用户服务专用的数据库配置
    database_url: str = Field(
        ..., 
        env="USER_SERVICE_DATABASE_URL",
        description="用户服务数据库连接URL"
    )
    database_pool_size: int = Field(
        default=10, 
        env="USER_SERVICE_DATABASE_POOL_SIZE",
        description="用户服务数据库连接池大小"
    )
    database_pool_timeout: int = Field(
        default=30, 
        env="USER_SERVICE_DATABASE_POOL_TIMEOUT",
        description="用户服务数据库连接超时"
    )
    database_echo: bool = Field(
        default=False, 
        env="USER_SERVICE_DATABASE_ECHO",
        description="是否输出SQL日志"
    )
    
    # 用户服务特定配置
    password_hash_rounds: int = Field(
        default=12, 
        env="USER_SERVICE_PASSWORD_HASH_ROUNDS",
        description="密码哈希轮数"
    )
    email_verification_required: bool = Field(
        default=True, 
        env="USER_SERVICE_EMAIL_VERIFICATION_REQUIRED",
        description="是否需要邮箱验证"
    )
    
    class Config:
        env_prefix = "USER_SERVICE_"
        env_file = ".env"


# ========================================
# 2. 交易服务 - 多数据库配置
# ========================================

class TradingServiceSettings(RedFireSettings, MultiDatabaseServiceMixin):
    """
    交易服务配置
    
    交易服务需要多个数据库：
    - MySQL: 交易数据和订单
    - InfluxDB: 时序数据（价格、成交量等）
    - Redis: 缓存和会话
    """
    
    # 主数据库 - MySQL (交易数据)
    primary_db_url: str = Field(
        ..., 
        env="TRADING_SERVICE_PRIMARY_DB_URL",
        description="交易服务主数据库URL"
    )
    primary_db_pool_size: int = Field(
        default=25, 
        env="TRADING_SERVICE_PRIMARY_DB_POOL_SIZE",
        description="主数据库连接池大小"
    )
    
    # 时序数据库 - InfluxDB
    influxdb_url: str = Field(
        ..., 
        env="TRADING_SERVICE_INFLUXDB_URL",
        description="InfluxDB连接URL"
    )
    influxdb_token: str = Field(
        ..., 
        env="TRADING_SERVICE_INFLUXDB_TOKEN",
        description="InfluxDB访问令牌"
    )
    influxdb_org: str = Field(
        default="redfire_trading", 
        env="TRADING_SERVICE_INFLUXDB_ORG",
        description="InfluxDB组织"
    )
    influxdb_bucket: str = Field(
        default="trading_data", 
        env="TRADING_SERVICE_INFLUXDB_BUCKET",
        description="InfluxDB存储桶"
    )
    
    # 只读副本数据库（可选）
    readonly_db_url: str = Field(
        default="", 
        env="TRADING_SERVICE_READONLY_DB_URL",
        description="只读副本数据库URL"
    )
    readonly_db_pool_size: int = Field(
        default=15, 
        env="TRADING_SERVICE_READONLY_DB_POOL_SIZE",
        description="只读数据库连接池大小"
    )
    
    # 交易服务特定配置
    max_order_size: float = Field(
        default=1000000.0, 
        env="TRADING_SERVICE_MAX_ORDER_SIZE",
        description="最大订单金额"
    )
    risk_check_enabled: bool = Field(
        default=True, 
        env="TRADING_SERVICE_RISK_CHECK_ENABLED",
        description="是否启用风险检查"
    )
    
    def get_database_configs(self) -> Dict[str, Dict[str, Any]]:
        """返回交易服务的多数据库配置"""
        configs = {
            "primary": {
                "url": self.primary_db_url,
                "pool_size": self.primary_db_pool_size,
                "pool_timeout": 30,
                "echo": self.is_development,
                "type": "mysql"
            },
            "timeseries": {
                "url": self.influxdb_url,
                "token": self.influxdb_token,
                "org": self.influxdb_org,
                "bucket": self.influxdb_bucket,
                "type": "influxdb"
            }
        }
        
        # 如果配置了只读副本，则添加
        if self.readonly_db_url:
            configs["readonly"] = {
                "url": self.readonly_db_url,
                "pool_size": self.readonly_db_pool_size,
                "pool_timeout": 30,
                "echo": False,
                "type": "mysql"
            }
        
        return configs
    
    class Config:
        env_prefix = "TRADING_SERVICE_"
        env_file = ".env"


# ========================================
# 3. 市场数据服务 - 专用时序数据库
# ========================================

class MarketDataServiceSettings(RedFireSettings, SingleDatabaseServiceMixin):
    """
    市场数据服务配置
    
    市场数据服务主要使用InfluxDB存储时序数据
    """
    
    # InfluxDB配置
    database_url: str = Field(
        ..., 
        env="MARKET_DATA_SERVICE_INFLUXDB_URL",
        description="InfluxDB连接URL"
    )
    influxdb_token: str = Field(
        ..., 
        env="MARKET_DATA_SERVICE_INFLUXDB_TOKEN",
        description="InfluxDB访问令牌"
    )
    influxdb_org: str = Field(
        default="redfire_market", 
        env="MARKET_DATA_SERVICE_INFLUXDB_ORG",
        description="InfluxDB组织"
    )
    influxdb_bucket: str = Field(
        default="market_data", 
        env="MARKET_DATA_SERVICE_INFLUXDB_BUCKET",
        description="InfluxDB存储桶"
    )
    
    # 市场数据特定配置
    data_retention_days: int = Field(
        default=365, 
        env="MARKET_DATA_SERVICE_DATA_RETENTION_DAYS",
        description="数据保留天数"
    )
    real_time_enabled: bool = Field(
        default=True, 
        env="MARKET_DATA_SERVICE_REAL_TIME_ENABLED",
        description="是否启用实时数据"
    )
    
    def get_database_configs(self) -> Dict[str, Dict[str, Any]]:
        """返回市场数据服务的InfluxDB配置"""
        return {
            "primary": {
                "url": self.database_url,
                "token": self.influxdb_token,
                "org": self.influxdb_org,
                "bucket": self.influxdb_bucket,
                "type": "influxdb",
                "retention_days": self.data_retention_days
            }
        }
    
    class Config:
        env_prefix = "MARKET_DATA_SERVICE_"
        env_file = ".env"


# ========================================
# 4. API网关 - 无数据库配置
# ========================================

class ApiGatewaySettings(RedFireSettings):
    """
    API网关配置
    
    API网关不需要数据库，只需要缓存和路由配置
    """
    
    # 路由配置
    upstream_timeout: int = Field(
        default=30, 
        env="API_GATEWAY_UPSTREAM_TIMEOUT",
        description="上游服务超时时间"
    )
    max_retries: int = Field(
        default=3, 
        env="API_GATEWAY_MAX_RETRIES",
        description="最大重试次数"
    )
    
    # 限流配置
    rate_limit_enabled: bool = Field(
        default=True, 
        env="API_GATEWAY_RATE_LIMIT_ENABLED",
        description="是否启用限流"
    )
    rate_limit_requests: int = Field(
        default=1000, 
        env="API_GATEWAY_RATE_LIMIT_REQUESTS",
        description="每分钟请求限制"
    )
    
    class Config:
        env_prefix = "API_GATEWAY_"
        env_file = ".env"


# ========================================
# 5. 通知服务 - MongoDB配置
# ========================================

class NotificationServiceSettings(RedFireSettings, SingleDatabaseServiceMixin):
    """
    通知服务配置
    
    通知服务使用MongoDB存储通知记录和模板
    """
    
    # MongoDB配置
    database_url: str = Field(
        ..., 
        env="NOTIFICATION_SERVICE_MONGODB_URL",
        description="MongoDB连接URL"
    )
    database_pool_size: int = Field(
        default=10, 
        env="NOTIFICATION_SERVICE_MONGODB_POOL_SIZE",
        description="MongoDB连接池大小"
    )
    
    # 通知服务特定配置
    email_enabled: bool = Field(
        default=True, 
        env="NOTIFICATION_SERVICE_EMAIL_ENABLED",
        description="是否启用邮件通知"
    )
    sms_enabled: bool = Field(
        default=False, 
        env="NOTIFICATION_SERVICE_SMS_ENABLED",
        description="是否启用短信通知"
    )
    push_enabled: bool = Field(
        default=True, 
        env="NOTIFICATION_SERVICE_PUSH_ENABLED",
        description="是否启用推送通知"
    )
    
    def get_database_configs(self) -> Dict[str, Dict[str, Any]]:
        """返回通知服务的MongoDB配置"""
        return {
            "primary": {
                "url": self.database_url,
                "pool_size": self.database_pool_size,
                "type": "mongodb",
                "echo": self.is_development
            }
        }
    
    class Config:
        env_prefix = "NOTIFICATION_SERVICE_"
        env_file = ".env"


# ========================================
# 使用示例
# ========================================

def create_service_configs():
    """创建各服务配置的示例"""
    
    # 1. 用户服务配置
    user_config = UserServiceSettings(
        service_name="user_service",
        database_url="mysql+aiomysql://user:pass@localhost:3306/users_db"
    )
    print("用户服务数据库配置:", user_config.get_database_configs())
    
    # 2. 交易服务配置
    trading_config = TradingServiceSettings(
        service_name="trading_service",
        primary_db_url="mysql+aiomysql://trading:pass@localhost:3306/trading_db",
        influxdb_url="http://localhost:8086",
        influxdb_token="your_influxdb_token"
    )
    print("交易服务数据库配置:", trading_config.get_database_configs())
    
    # 3. 市场数据服务配置
    market_config = MarketDataServiceSettings(
        service_name="market_data_service",
        database_url="http://localhost:8086",
        influxdb_token="your_market_token"
    )
    print("市场数据服务数据库配置:", market_config.get_database_configs())
    
    # 4. API网关配置（无数据库）
    gateway_config = ApiGatewaySettings(
        service_name="api_gateway"
    )
    print("API网关配置 - 无数据库")
    
    # 5. 通知服务配置
    notification_config = NotificationServiceSettings(
        service_name="notification_service",
        database_url="mongodb://localhost:27017/notifications_db"
    )
    print("通知服务数据库配置:", notification_config.get_database_configs())


if __name__ == "__main__":
    create_service_configs()


# ========================================
# 环境变量配置示例
# ========================================

"""
# .env 文件示例

# 用户服务配置
USER_SERVICE_DATABASE_URL=mysql+aiomysql://user_app:user_pass@localhost:3306/redfire_users
USER_SERVICE_DATABASE_POOL_SIZE=10
USER_SERVICE_PASSWORD_HASH_ROUNDS=12
USER_SERVICE_EMAIL_VERIFICATION_REQUIRED=true

# 交易服务配置
TRADING_SERVICE_PRIMARY_DB_URL=mysql+aiomysql://trading_app:trading_pass@localhost:3306/redfire_trading
TRADING_SERVICE_PRIMARY_DB_POOL_SIZE=25
TRADING_SERVICE_INFLUXDB_URL=http://localhost:8086
TRADING_SERVICE_INFLUXDB_TOKEN=your_trading_influxdb_token
TRADING_SERVICE_INFLUXDB_ORG=redfire_trading
TRADING_SERVICE_INFLUXDB_BUCKET=trading_data
TRADING_SERVICE_READONLY_DB_URL=mysql+aiomysql://readonly:readonly_pass@localhost:3307/redfire_trading
TRADING_SERVICE_MAX_ORDER_SIZE=1000000.0
TRADING_SERVICE_RISK_CHECK_ENABLED=true

# 市场数据服务配置
MARKET_DATA_SERVICE_INFLUXDB_URL=http://localhost:8086
MARKET_DATA_SERVICE_INFLUXDB_TOKEN=your_market_influxdb_token
MARKET_DATA_SERVICE_INFLUXDB_ORG=redfire_market
MARKET_DATA_SERVICE_INFLUXDB_BUCKET=market_data
MARKET_DATA_SERVICE_DATA_RETENTION_DAYS=365
MARKET_DATA_SERVICE_REAL_TIME_ENABLED=true

# API网关配置
API_GATEWAY_UPSTREAM_TIMEOUT=30
API_GATEWAY_MAX_RETRIES=3
API_GATEWAY_RATE_LIMIT_ENABLED=true
API_GATEWAY_RATE_LIMIT_REQUESTS=1000

# 通知服务配置
NOTIFICATION_SERVICE_MONGODB_URL=mongodb://notification_user:notification_pass@localhost:27017/redfire_notifications
NOTIFICATION_SERVICE_MONGODB_POOL_SIZE=10
NOTIFICATION_SERVICE_EMAIL_ENABLED=true
NOTIFICATION_SERVICE_SMS_ENABLED=false
NOTIFICATION_SERVICE_PUSH_ENABLED=true

# 框架通用配置
REDFIRE_JWT_SECRET_KEY=your_super_secret_jwt_key_at_least_32_chars
REDFIRE_JWT_ALGORITHM=HS256
REDFIRE_JWT_EXPIRE_MINUTES=30
REDFIRE_REDIS_URL=redis://localhost:6379/0
REDFIRE_ENVIRONMENT=development
"""
